// pages/order/index.js
Page({
  data: {
    active: 0,
    orderList: [],
    loading: true,
    finished: false,
    tabs: [
      { title: '全部', status: '' },
      { title: '待付款', status: 'unpaid' },
      { title: '待发货', status: 'paid' },
      { title: '待收货', status: 'shipped' },
      { title: '已完成', status: 'completed' }
    ],
    currentPage: 1,
    pageSize: 10,
    currentStatus: ''
  },

  onLoad: function (options) {
    // 如果从其他页面跳转过来并指定了状态，则切换到对应标签
    if (options.status) {
      const index = this.data.tabs.findIndex(tab => tab.status === options.status);
      if (index !== -1) {
        this.setData({ active: index, currentStatus: options.status });
      }
    }
    
    this.loadOrderList();
  },

  onPullDownRefresh: function () {
    this.resetAndReload();
    wx.stopPullDownRefresh();
  },

  onReachBottom: function () {
    if (!this.data.finished) {
      this.loadMoreOrders();
    }
  },

  // 切换标签
  onTabChange: function (event) {
    const index = event.detail.index;
    const status = this.data.tabs[index].status;
    
    this.setData({
      active: index,
      currentStatus: status,
      currentPage: 1,
      orderList: [],
      loading: true,
      finished: false
    });
    
    this.loadOrderList();
  },

  // 加载订单列表
  loadOrderList: function () {
    const { currentPage, pageSize, currentStatus, orderList } = this.data;
    
    // 显示加载状态
    this.setData({ loading: true });
    
    // 模拟API请求，实际开发中应替换为真实的API调用
    setTimeout(() => {
      // 模拟获取订单数据
      const newOrders = this.getMockOrders(currentPage, pageSize, currentStatus);
      
      // 更新数据
      this.setData({
        orderList: [...orderList, ...newOrders],
        loading: false,
        finished: newOrders.length < pageSize,
        currentPage: currentPage + 1
      });
    }, 1000);
  },

  // 加载更多订单
  loadMoreOrders: function () {
    if (!this.data.loading) {
      this.loadOrderList();
    }
  },

  // 重置并重新加载
  resetAndReload: function () {
    this.setData({
      currentPage: 1,
      orderList: [],
      loading: true,
      finished: false
    });
    
    this.loadOrderList();
  },

  // 查看订单详情
  viewOrderDetail: function (event) {
    const orderId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/order-detail/index?id=${orderId}`
    });
  },

  // 取消订单
  cancelOrder: function (event) {
    const orderId = event.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确定要取消此订单吗？',
      success: (res) => {
        if (res.confirm) {
          // 模拟取消订单API调用
          wx.showLoading({ title: '处理中...' });
          
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '订单已取消',
              icon: 'success'
            });
            
            // 重新加载订单列表
            this.resetAndReload();
          }, 1000);
        }
      }
    });
  },

  // 去支付
  goPay: function (event) {
    const orderId = event.currentTarget.dataset.id;
    // 实际开发中应跳转到支付页面或调用支付API
    wx.showToast({
      title: '跳转到支付...',
      icon: 'none'
    });
  },

  // 确认收货
  confirmReceipt: function (event) {
    const orderId = event.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确认已收到商品？',
      success: (res) => {
        if (res.confirm) {
          // 模拟确认收货API调用
          wx.showLoading({ title: '处理中...' });
          
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '已确认收货',
              icon: 'success'
            });
            
            // 重新加载订单列表
            this.resetAndReload();
          }, 1000);
        }
      }
    });
  },

  // 模拟获取订单数据
  getMockOrders: function (page, pageSize, status) {
    const mockOrders = [];
    const startIndex = (page - 1) * pageSize;
    const orderStatuses = ['unpaid', 'paid', 'shipped', 'completed', 'cancelled'];
    
    // 生成模拟数据
    for (let i = 0; i < pageSize; i++) {
      const index = startIndex + i;
      
      // 如果已经生成了足够多的订单，则停止
      if (index >= 30) break;
      
      // 随机生成订单状态，或使用指定的状态
      let orderStatus = orderStatuses[Math.floor(Math.random() * orderStatuses.length)];
      if (status && status !== '') {
        orderStatus = status;
      }
      
      // 根据状态设置订单的其他属性
      const orderDate = new Date();
      orderDate.setDate(orderDate.getDate() - Math.floor(Math.random() * 30));
      
      mockOrders.push({
        id: `ORDER${100000 + index}`,
        status: orderStatus,
        statusText: this.getStatusText(orderStatus),
        totalAmount: (Math.random() * 1000 + 50).toFixed(2),
        createTime: orderDate.toISOString().split('T')[0],
        items: [
          {
            id: `ITEM${200000 + index * 2}`,
            name: `商品${index + 1}`,
            price: (Math.random() * 200 + 10).toFixed(2),
            quantity: Math.floor(Math.random() * 5) + 1,
            image: 'https://img.yzcdn.cn/vant/cat.jpeg'
          },
          {
            id: `ITEM${200000 + index * 2 + 1}`,
            name: `商品${index + 2}`,
            price: (Math.random() * 200 + 10).toFixed(2),
            quantity: Math.floor(Math.random() * 3) + 1,
            image: 'https://img.yzcdn.cn/vant/cat.jpeg'
          }
        ]
      });
    }
    
    return mockOrders;
  },

  // 获取状态文本
  getStatusText: function (status) {
    const statusMap = {
      'unpaid': '待付款',
      'paid': '待发货',
      'shipped': '待收货',
      'completed': '已完成',
      'cancelled': '已取消'
    };
    
    return statusMap[status] || '未知状态';
  }
});